#include "loggerc.h"

int lenRecord;
int flagDebug;

void setDebugON()
{
    flagDebug = DEBUG;
};

void setDebugOFF()
{
    flagDebug = NODEBUG;
};

void writelog (
   int log_file,					// FILE DI LOG
   int log_level,					// livello di errore (INF, DBG, WRN, ERR)
   char *p_desc                     // descrizione
)
{
    char log_record[4000];

    memset(log_record,'\0',4000);

    pspTime psptime;
    sceRtcGetCurrentClockLocalTime(&psptime);

    if (log_level == ERR ) {
        sprintf(log_record,"[ %d/%d/%d %d:%d ] - [ERR] - %s",psptime.day,psptime.month,psptime.year,psptime.hour,psptime.minutes,p_desc);
        //printf("%s\n",log_record);
        sceIoWrite(log_file, log_record,strlen(log_record));
    }
    else if(log_level == WRN) {
        sprintf(log_record,"[ %d/%d/%d %d:%d ] - [WRN] - %s",psptime.day,psptime.month,psptime.year,psptime.hour,psptime.minutes,p_desc);
        //printf("%s\n",log_record);
        sceIoWrite(log_file, log_record,strlen(log_record));
    }
    else if (log_level == INF ) {
        sprintf(log_record,"[ %d/%d/%d %d:%d ] - [INF] - %s",psptime.day,psptime.month,psptime.year,psptime.hour,psptime.minutes,p_desc);
        //printf("%s\n",log_record);
        sceIoWrite(log_file, log_record,strlen(log_record));
    }
    else if (log_level == DBG && flagDebug == DEBUG){
        sprintf(log_record,"[ %d/%d/%d %d:%d ] - [DBG] - %s",psptime.day,psptime.month,psptime.year,psptime.hour,psptime.minutes,p_desc);
        //printf("%s\n",log_record);
        sceIoWrite(log_file, log_record,strlen(log_record));
    }
};

int initLog( char *path, int lenStrRecord, int trace )
{
	if (lenRecord > 4000) lenStrRecord = 4000;
	else if (lenRecord < 170) lenStrRecord = 170;
	flagDebug = trace;
	int fd = sceIoOpen(path, PSP_O_WRONLY|PSP_O_CREAT|PSP_O_APPEND, 0777);
	writelog(fd, INF, "START LOG ------------\n");
	if ( trace == DEBUG ) writelog(fd, INF, "DEBUG : Enable\n");
	return fd;
};

void deinitLog(int fd)
{
   writelog(fd, INF, "END LOG ------------\n");
   sceIoClose(fd);
};
